﻿using LibBinary.DataSource;
using LibBinary.FileData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibBinary.FileDeclaration.Text
{
    public class ArrayDeclaration : IFileDeclaration
    {
        private readonly IFileDeclaration item;

        public ArrayDeclaration(IFileDeclaration item)
        {
            this.item = item;
        }

        public AbstractFileData Read(TextFileInputSource src, AbstractFileData parentNode)
        {
            var structData = new StructuredData(parentNode);

            var fieldDataCount = new FieldData(structData) { FieldName = "count" };
            var fieldDataData = new FieldData(structData) { FieldName = "data" };
            structData.Data = new AbstractFileData[] { fieldDataCount, fieldDataData };

            List<AbstractFileData> items = new List<AbstractFileData>();
            src.SkipChar('[');
            if (!src.TrySkipChar(']'))
            {
                items.Add(item.Read(src, structData.Data[1]));
                bool endSkipped = false;
                while (src.TrySkipChar(','))
                {
                    if (src.TrySkipChar(']'))
                    {
                        endSkipped = true;
                        break;
                    }
                    items.Add(item.Read(src, structData.Data[1]));
                }
                if (!endSkipped)
                {
                    src.SkipChar(']');
                }
            }

            fieldDataCount.Data = new SystemPrimitiveData(fieldDataCount, items.Count);
            fieldDataData.Data = new ArrayData(fieldDataData) { Data = items.ToArray() };
            return structData;
        }

        public void Write(TextFileOutputSource src, AbstractFileData data)
        {
            throw new NotImplementedException();
        }
    }
}
